<?php

namespace App\Repositories;

use App\Enums\FlyingEnum;
use App\Enums\RedisKeyEnum;
use App\Services\Tools\TimeService;
use App\Services\Tools\HelperService;
use App\Traits\GiftRank;
use Illuminate\Support\Facades\DB;
use App\Exceptions\BasicException;

class FlyingRepository
{
    use GiftRank;

    /**
     * @Desc:奖池列表
     * @param $type
     * @param $is_next
     * @return \Illuminate\Support\Collection
     * @author: shiquan
     * @Time: 2023/3/7 10:56
     */
    public function getJackpotList($type, $is_next = false)
    {
        $model = $is_next ? app('model_flying_next')->getTable() : app('model_flying_pool')->getTable();
        $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.$model.' as a')
                  ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
                  ->select([
                      'a.id',
                      'a.gift_id',
                      'a.number',
                      'a.critical_times',
                      'a.ratio',
                      'b.name as gift_name',
                      'b.price',
                      'b.picture',
                      'b.special',
                  ])
                  ->where('a.type', $type)
                  ->orderBy('b.price', 'desc')
                  ->orderBy('b.id', 'desc')
                  ->get()->map(function ($item, $key) {
                $item->quality = $this->giftRank($item->price);
                $item->key = $key + 1;

                return $item;
            });

        return $list;
    }

    /**
     * @Desc:下期奖池列表
     * @param $id
     * @param $is_next
     * @return \Illuminate\Support\Collection
     * @author: shiquan
     * @Time: 2023/3/7 15:43
     */
    public function getJackpotNextList($id, $is_next = false)
    {
        $model = $is_next ? app('model_flying_next')->getTable() : app('model_flying_pool')->getTable();
        $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.$model.' as a')
                  ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
                  ->select([
                      'a.id',
                      'a.gift_id',
                      'a.number',
                      'a.critical_times',
                      'a.ratio',
                      'b.name as gift_name',
                      'b.price',
                      'b.picture',
                      'b.special',
                  ])
                  ->where('a.next_config_id', $id)
                  ->orderBy('b.price', 'desc')
                  ->orderBy('b.id', 'desc')
                  ->get()->map(function ($item, $key) {
                $item->quality = $this->giftRank($item->price);
                $item->key = $key + 1;

                return $item;
            });

        return $list;
    }

    /**
     * @Desc:获取剩余次数
     * @param $type
     * @param $is_next
     * @return int
     * @author: shiquan
     * @Time: 2023/3/7 10:54
     */
    public function getJackpotCount($type = 1, $is_next = false, $nextConfigId = false)
    {
        $model = $is_next ? 'model_flying_next' : 'model_flying_pool';
        if ($nextConfigId){
            $total = app($model)->where('next_config_id', $nextConfigId)->sum('number');
        } else {
            $total = app($model)->where('type', $type)->sum('number');
        }

        return $total ?: 0;
    }

    /**
     * @Desc:获取剩余总金额
     * @param $type
     * @param $is_next
     * @return int|mixed
     * @author: shiquan
     * @Time: 2023/3/7 10:54
     */
    public function getJackpotTotal($type = 1, $is_next = false, $nextConfigId = false)
    {
        $model = $is_next ? app('model_flying_next')->getTable() : app('model_flying_pool')->getTable();
        $total = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.$model.' as a')
                   ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
                    ->where(function ($query) use ($nextConfigId){
                        if ($nextConfigId){
                            $query->where('next_config_id', $nextConfigId);
                        }
                    })
                   ->where('a.type', $type)

                   ->sum(DB::raw('a.number * b.price'));

        return $total ?: 0;
    }

    /**
     * @Desc:替换奖池
     * @param $type
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 13:36
     */
    public function replaceJackpot($type)
    {
        $type_next_map = FlyingEnum::POOL_TYPE_MAP[$type];
        $nextConfigIds = app('model_flying_next_config')->where('type', $type_next_map)->where('is_open' ,1)->pluck('id')->toArray();
        if (empty($nextConfigIds)){
            throw new BasicException(0, '下期奖池为空');
        }
        $nextConfigId = $nextConfigIds[mt_rand(0,count($nextConfigIds) - 1)];

        $nextPrizeConfig = $this->getJackpotNext($nextConfigId);
        $oldList = app('model_flying_pool')->where('type', $type)->get()->toArray();
        if(!empty($oldList)){
            $oldList=  HelperService::indexToAssoc($oldList,'gift_id');
        }
        $insertList = [];
        foreach ($nextPrizeConfig as $item) {
            $oldCriticalNum = isset($oldList[$item['gift_id']])?$oldList[$item['gift_id']]['critical_times']:0;
            $insertList[] = [
                "type"     => $type,
                "number"   => $item['number'],
                "critical_times"   => $item['critical_times']+$oldCriticalNum,
                "gift_id"  => $item['gift_id'],
                "add_time" => date("Y-m-d H:i:s"),
                "remark"   => "由下期奖池覆盖替换而来",
            ];
        }
        if (!empty($insertList)) {
            DB::beginTransaction();
            try {
                app('model_flying_pool')->where('type', $type)->delete();
                app('model_flying_pool')->insert($insertList);
            }catch (\Exception $e){
                DB::rollBack();
                throw new BasicException(0, $e->getMessage());
            }
            DB::commit();
        }
    }

    /**
     * @Desc:获取下期奖池
     * @param $type
     * @return array
     * @author: shiquan
     * @Time: 2023/3/7 13:47
     */
    public function getJackpotNext($nextConfigId)
    {
        $where = [
            ['a.sold', 1],
            ['a.next_config_id', $nextConfigId],
        ];

        $list =  app('model_flying_next')->from(\DB::raw(config('database.connections.mysql_flying.database')).'.'.'flying_next as a')
                  ->LeftJoin(\DB::raw(config('database.connections.mysql.database')).'.'.'ln_gift as b', 'b.id', '=', 'a.gift_id')
                  ->select([
                      'a.gift_id',
                      'a.number',
                      'a.critical_times',
                      'a.ratio',
                      'b.price',
                      'a.type',
                  ])
                  ->where($where)
                  ->orderBy('a.ratio', 'desc')->get()->toArray();
        $list = empty($list)?[]:$list;
        return $list;
    }

    /**
     * @Desc:中奖记录
     * @param $request
     * @return array
     * @author: shiquan
     * @Time: 2023/3/7 14:05
     */
    public function getRecord($request)
    {
        $isFlutter = $request->input('is_flutter', -1);
        $datemin = strtotime($request->input('datemin', 0));
        $datemax = $request->input('datemax', 0);
        $datemax = strtotime($datemax." 23:59:59");
        $where = [];
        //条件查询
        if (!empty($datemin) && !empty($datemax)) {
            $where [] = [
                function ($query) use ($datemin, $datemax) {
                    $query->whereBetween('a.add_time', [$datemin, $datemax]);
                },
            ];
        } elseif (!empty($datemin)) {
            $where[] = ['a.add_time', '>=', $datemin];
        } elseif (!empty($datemax)) {
            $where[] = ['a.add_time', '<=', $datemax];
        }
        $keyword = $request->input('keyword', '');
        if ($keyword) {
            $user_ids = app('model_user_data')->where('user_code', '=', "$keyword")->orWhere('nickname', '=',
                "$keyword")->pluck('user_id');
            if ($user_ids) {
                $where[] = [
                    function ($query) use ($user_ids) {
                        $query->whereIn('a.user_id', $user_ids);
                    },
                ];
            }
        }

        $gift_id = $request->input('gift_id', 0);
        if ($gift_id > 0) {
            $where[] = ['a.gift_id', $gift_id];
        }

        if ($isFlutter == 1) {
            $where[] = ['c.price', '>=', 99999];
        } else if ($isFlutter == 0) {
            $where[] = ['c.price', '<', 99999];
        }

        $field = [
            'a.id',
            'a.user_id',
            'a.gift_id',
            'a.add_time',
            'a.number',
            'b.nickname',
            'c.name as gift_name',
            'c.price as gift_price',
            'b.user_code',
        ];
        $perPage = $request->input('perPage', 20);
        $page = $request->input('page', 1);

        if(!empty($where)){
            $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.'flying_gift_log as a')->select($field)
                ->leftJoin('ln_user_data as b', 'a.user_id', '=', 'b.user_id')
                ->leftJoin('ln_gift as c', 'a.gift_id', '=', 'c.id')
                ->where($where)->orderByDesc('a.id')->paginate($perPage);
            $data = $list->items();
            $page = $list->currentPage();
            $limit = $list->perPage();
            $next = $list->nextPageUrl();
            $total = $list->total();
            $request = [
                'list' => $data,
                'meta' => [
                    'page' => $page,
                    'limit' => $limit,
                    'next' => $next,
                    'total' => $total
                ]
            ];
        }else{
            $minId = app('model_flying_log')->min('id');
            $maxId = app('model_flying_log')->max('id');
            $endId = $maxId - ($page - 1) * $perPage;
            $startId = $endId - $perPage;
            $where = [['a.id', '>', $startId], ['a.id', '<=', $endId]];
            $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.'flying_gift_log as a')->select($field)
                ->leftJoin('ln_user_data as b', 'a.user_id', '=', 'b.user_id')
                ->leftJoin('ln_gift as c', 'a.gift_id', '=', 'c.id')
                ->where($where)
                ->orderByDesc('a.id')
                ->get()->toArray();
            $request = [
                'list' => $list,
                'meta' => [
                    'limit' => $perPage,
                    'next' => null,
                    'page' => $page,
                    'total' => $maxId - $minId + 1,
                    ]
            ];
        }
        return $request;
//        return $list;
    }

    /**
     * @Desc:统计数据-总数据
     * @return array
     * @author: shiquan
     * @Time: 2023/3/7 14:45
     */
    public function allData()
    {
        //总
        $allTotal = $this->getData(strtotime(date('2023-03-07 00:00:00')));

        //日
        $todayRes = TimeService::today();
        $dayTotal = $this->getData($todayRes[0], $todayRes[1]);

        //周
        $weekRes = TimeService::week();
        $weekTotal = $this->getData($weekRes[0], $weekRes[1]);

        //月
        $monthRes = TimeService::month();
        $monthTotal = $this->getData($monthRes[0], $monthRes[1]);

        $res = [
            'all_total'   => $allTotal,
            'day_total'   => $dayTotal,
            'week_total'  => $weekTotal,
            'month_total' => $monthTotal,
        ];

        return $res;
    }

    /**
     * @Desc:
     * @param $startTime
     * @param $endTime
     * @return int[]
     * @author: shiquan
     * @Time: 2023/3/8 16:12
     */
    public function getData($startTime = '', $endTime = '')
    {
        //$where = [['game_type', '=', 3]];
        $where = [];
        if (!empty($startTime) && !empty($endTime)) {
            $where[] = ['add_time', '>=', $startTime];
            $where[] = ['add_time', '<=', $endTime];
        } elseif (!empty($startTime)){
            $where[] = ['add_time', '>=', $startTime];
        }

        $totalData = app('model_flying_gold_price')
            ->where($where)
            ->selectRaw('user_id, sum(number) as outcoin_total, sum(total_cost) as incoin_total, sum(total_cost) - sum(number) as profit_loss_total')
            ->groupBy('user_id')
            ->get()->toArray();

        $res = [
            'incoin_total'      => 0,/*飞屋总投入*/
            'outcoin_total'     => 0,/*飞屋总产出*/
            'profit_loss_total' => 0,/*平台盈亏*/
            'profit_number'     => 0,/*平台盈人数*/
            'loss_number'       => 0,/*平台亏人数*/
        ];
        if (!empty($totalData)){
            foreach ($totalData as $v) {
                $res['incoin_total'] += $v['incoin_total'];
                $res['outcoin_total'] += $v['outcoin_total'];
                $res['profit_loss_total'] += $v['profit_loss_total'];
                if ($v['incoin_total'] > $v['outcoin_total']) {
                    $res['profit_number'] += 1;
                } else {
                    $res['loss_number'] += 1;
                }
            }
        }
        $res['profit_loss_number'] = $res['profit_number'].'/'.$res['loss_number'];
        unset($res['profit_number']);
        unset($res['loss_number']);

        return $res;
    }

    /**
     * @Desc:数据统计列表信息
     * @param $params
     * @return array
     * @author: shiquan
     * @Time: 2023/3/8 16:12
     */
    public function userList($params)
    {
        //条件
        $where = [];
        //盈亏分类，并替换页码数
        if ($params['type'] == 1){
            $phase = '>0';
        } else {
            $phase = '<0';
        }
        $page = $params['page'];
        $perPage = $params['page_size'];
        //时间筛选
        if (!empty($params['start_time'])){
            $where[] = ['add_time', '>=', strtotime($params['start_time'])];
        }
        if (!empty($params['end_time'])){
            $where[] = ['add_time', '<=', strtotime($params['end_time'])];
        }
        //编写sql
        $model = app('model_flying_gold_price')->where($where);
        $modelTotal = app('model_flying_gold_price')->where($where);
        //用户code筛选
        if (isset($params['user_code']) && $params['user_code'] != -1){
            $userId = app('model_user_data')->where('user_code', 'like', "%" .$params['user_code'] . "%")->get(['user_id'])->toArray();
            $userIds = array_column($userId, 'user_id');
            $model = $model->whereIn('user_id', $userIds);
            $modelTotal = $modelTotal->whereIn('user_id', $userIds);
        }
        //执行sql
        $data = $model->groupBy('user_id')
            ->select(['user_id', DB::raw('max(add_time) as last_time'), DB::raw('sum(total_cost) as put_data'), DB::raw('sum(number) as get_data')])
            ->orderBy(DB::raw('max(add_time)'), 'desc')
            ->havingRaw('sum(total_cost) - sum(number)' . $phase)
            ->paginate($perPage, ['*'], '', $page)->toArray();
        //列表头部统计数据
        $totalData = $modelTotal
            ->select(['user_id', DB::raw('sum(total_cost) as put_data'), DB::raw('sum(number) as get_data')])
            ->havingRaw('sum(total_cost) - sum(number)' . $phase)
            ->groupBy('user_id')->get()->toArray();
        //拿出结果中所有的user_id，查询用户信息
        $tmpUserIds = array_column($data['data'], 'user_id');
        $userData = app('model_user_data')->whereIn('user_id', $tmpUserIds)->get(['user_id', 'user_code', 'nickname'])->toArray();
        //处理用户信息数组
        $tmpUserDataIds = array_column($userData, 'user_id');
        $tmpUserData = array_column($userData, null, 'user_id');
        //整理结果
        $list = [];
        $total = [
            'total_num' => 0,
            'total_put' => 0,
            'total_get' => 0,
            'total_phase' => 0,
        ];
        if (!empty($totalData)){
            $total = [
                'total_num' => count($totalData),
                'total_put' => array_sum(array_column($totalData, 'put_data')),
                'total_get' => array_sum(array_column($totalData, 'get_data')),
                'total_phase' => array_sum(array_column($totalData, 'put_data')) - array_sum(array_column($totalData, 'get_data'))
            ];
        }
        //循环处理结果集
        foreach ($data['data'] as $key => $value){
            //用户编号合昵称赋值
            $userCode = '';
            $nickname = '';
            if (in_array($value['user_id'], $tmpUserDataIds)){
                $userCode = $tmpUserData[$value['user_id']]['user_code'];
                $nickname =  $tmpUserData[$value['user_id']]['nickname'];
            }
            //数组赋值
            $list[] = [
                'id' => $key + 1,
                'user_code' => $userCode,
                'nickname' => $nickname,
                'incoin_total' => $value['put_data'],
                'outcoin_total' => $value['get_data'],
                'sum_profit_loss_total' => ($value['put_data'] - $value['get_data']),
                'last_drawn_time' => date('Y-m-d H:i:s', $value['last_time'])
            ];
        }

        return [
            'profit_loss_number' => $total['total_num'],
            'incoin_total' => $total['total_put'],
            'outcoin_total' => $total['total_get'],
            'profit_loss_total' => $total['total_phase'],
            'list' => [
                'data' => $list,
                'current_page' => $data['current_page'],
                'per_page' => $data['per_page'],
                'next_page_url' => $data['next_page_url'],
                'total' => $data['total']
            ]
        ];
    }

    /**
     * @Desc:下期奖池列表
     * @return mixed
     * @author: shiquan
     * @Time: 2023/3/8 16:11
     */
    public function getNextConfig()
    {
        $list = app("model_flying_next_config")
            ->select('id', 'name', 'type', 'is_open')
            ->orderBy('id', 'desc')
            ->get()->toArray();
        if (empty($list)) return [];
        foreach ($list as &$item) {
            $item['type_name'] = FlyingEnum::POOL_TYPE_CONFIG_NEXT[$item['type']] ?? '';
        }

        return $list;
    }

    /**
     * @Desc:新增下期奖池
     * @param $param
     * @return mixed
     * @author: shiquan
     * @Time: 2023/3/8 16:11
     */
    public function nextConfigAdd($param)
    {
        $res = app("model_flying_next_config")->insert([
            'name' => $param['name'],
            'type' => $param['type'],
        ]);

        return $res;
    }

    /**
     * @Desc:编辑下期奖池
     * @param $param
     * @return mixed
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 16:12
     */
    public function nextConfigEdit($param)
    {
        $luckyTreeNextConfigRes = app("model_flying_next_config")->where(['id' => $param['id']])->first();
        if (empty($luckyTreeNextConfigRes)) {
            throw new BasicException(110001);
        }
        if ($luckyTreeNextConfigRes['is_open'] == 1) {
            throw new BasicException(111002);
        }

        $res = app("model_flying_next_config")->where(['id' => $param['id']])->update([
            'name' => $param['name'],
            'type' => $param['type'],
        ]);

        return $res;
    }

    /**
     * @Desc:删除下期奖池
     * @param $param
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 16:13
     */
    public function nextConfigDel($param)
    {
        $luckyTreeNextConfigRes = app("model_flying_next_config")->where(['id' => $param['id']])->first();
        if (empty($luckyTreeNextConfigRes)) {
            throw new BasicException(110001);
        }
        if ($luckyTreeNextConfigRes['is_open'] == 1) {
            throw new BasicException(111003);
        }

        //开启事务
        DB::connection('mysql_flying')->beginTransaction();
        try {
            $luckyTreeNextConfigDel = app("model_flying_next_config")->where(['id' => $param['id']])->delete();
            if (!$luckyTreeNextConfigDel){
                throw new BasicException(10001, '删除失败');
            }
            //如果被删除的是百连池,那么就需要删除补池的礼物
            if ($luckyTreeNextConfigRes['type'] == FlyingEnum::POOL_TYPE_HUNDRED_NEXT){
                $giftIds = app('model_flying_next')->where('next_config_id', $param['id'])->pluck('gift_id')->toArray();
                app('model_flying_supplement_gift')->whereIn('gift_id', $giftIds)->update([
                    'is_open' => 1
                ]);
            }

            $luckyTreeNextDel = app('model_flying_next')->where(['next_config_id' => $param['id']])->delete();
            if ($luckyTreeNextDel === false) {
                throw new BasicException(10001, '删除失败');
            }

            DB::connection('mysql_flying')->commit();
        } catch (\Exception $e) {
            DB::connection('mysql_flying')->rollBack();
            throw new BasicException(10001, '删除失败');
        }

        return true;
    }

    /**
     * @Desc:下期奖池配置开关
     * @param $param
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/7 16:10
     */
    public function nextConfigOpen($param)
    {
        $luckyTreeNextConfigRes = app("model_flying_next_config")->where(['id' => $param['id']])->first();
        if (empty($luckyTreeNextConfigRes)){
            throw new BasicException(0, '不存在该配置');
        }
        if ($luckyTreeNextConfigRes['is_open'] == 1) {
            $isOpen = 0;
        } else {
            $isOpen = 1;
        }
        app("model_flying_next_config")->where(['id' => $param['id']])->update([
            'is_open' => $isOpen
        ]);
        return $isOpen;
    }

    /**
     * @Desc:补池设置配置
     * @return array
     * @author: shiquan
     * @Time: 2023/3/8 10:23
     */
    public function supplementConfigInfo()
    {
        $jackpotMoney = app('redis')->get(RedisKeyEnum::FLYING_JACKPOT_MONEY) ?? 0;
        $supplementConfigInfo = app('model_flying_supplement_config')->where('id', 1)->first();     //可以存在redis
        return [
            'jackpot_money' => $jackpotMoney,                       //剩余奖池价值
            'rate' => $supplementConfigInfo['rate'] ?? 0,           //当前比例
            'min_num' => $supplementConfigInfo['min_num'] ?? 0      //最低下限
        ];
    }

    /**
     * @Desc:更新补池配置
     * @param $params
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 10:28
     */
    public function supplementConfigUpdate($params)
    {
        $supplementConfigInfo = app('model_flying_supplement_config')->where('id', 1)->first();
        if (empty($supplementConfigInfo)){
            app('model_flying_supplement_config')->insert([
                'id' => 1,
                'rate' => $params['rate'] ?? 0,
                'min_num' => $params['min_num'] ?? 0,
                'update_time' => time(),
            ]);
        } else {
            $data = [];
            if (!empty($params['rate'])){
                $data['rate'] = $params['rate'];
            }
            if (isset($params['min_num']) && ($params['min_num'] !== '' || $params['min_num'] !== null)){
                $data['min_num'] = $params['min_num'];
            }
            if (empty($data)){
                throw new BasicException(0, '请输入正确参数');
            }
            $data['update_time'] = time();
            app('model_flying_supplement_config')->where('id', 1)->update($data);
        }
        $redisKey = RedisKeyEnum::FLYING_SUPPLEMENT_CONFIG;
        if (app('redis')->exists($redisKey)){
            app('redis')->del($redisKey);
        }
        return true;
    }

    /**
     * @Desc:补池列表
     * @return array
     * @author: shiquan
     * @Time: 2023/3/8 10:37
     */
    public function supplementGiftList()
    {
        $model = app('model_flying_supplement_gift')->getTable();
        $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.$model.' as a')
            ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
            ->select([
                'a.id',
                'a.gift_id',
                'a.update_time',
                'a.create_time',
                'b.name as gift_name',
                'b.price',
                'b.picture',
            ])
            ->where('a.is_delete', 0)
            ->orderBy('a.id', 'desc')
            ->get()->toArray();

        return $list;
    }

    /**
     * @Desc:补池获取礼物筛选列表
     * @param $type
     * @return array
     * @author: shiquan
     * @Time: 2023/3/8 11:09
     */
    public function nextCommonGifts($type)
    {
        $model = app('model_flying_next')->getTable();
        $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.$model.' as a')
            ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
            ->select([
                'a.gift_id',
                'b.name as gift_name',
                'b.price',
            ])
            ->where('a.type', $type)
            ->orderBy('a.id', 'desc')
            ->get()->toArray();
        return $list;
    }

    /**
     * @Desc:新增或者删除补池礼物
     * @param $params
     * @author: shiquan
     * @Time: 2023/3/8 11:14
     */
    public function supplementGiftUpdate($params)
    {
        $data['gift_id'] = $params['gift_id'];
        $data['weight_num'] = $params['weight_num'] ?? 1;
        $data['update_time'] = time();
        if ($params['id'] > 0){
            app('model_flying_supplement_gift')->where('id', $params['id'])->update($data);
        } else {
            $data['create_time'] = time();
            app('model_flying_supplement_gift')->insert($data);
        }
    }

    /**
     * @Desc:补池礼物删除
     * @param $params
     * @author: shiquan
     * @Time: 2023/3/8 11:15
     */
    public function supplementGiftDel($params)
    {
        $data['update_time'] = time();
        $data['is_delete'] = 1;
        app('model_flying_supplement_gift')->where('id', $params['id'])->update($data);
    }

    /**
     * @Desc:暴击配置
     * @param $params
     * @return array|mixed
     * @author: shiquan
     * @Time: 2023/3/8 15:28
     */
    public function criticalConfig()
    {
        $info = app('model_flying_critical_config')->where('id', 1)->first();
        if (empty($info)){
            return [];
        } else {
            $info = json_decode($info['config'], true);
            // 将二维数组中ids值的'1,2,3'的同级新增几个礼物名称
            if ($info){
                $ids = array_column($info, 'ids');
                $newIds = '';
                foreach ($ids as $key => $value){
                    $newIds = $newIds.','.$value;
                }
                $newIds = ltrim($newIds, ',');
                $newIdsArray = array_unique(explode(',', $newIds)); //将所有的自增id整合在一起
                //获取所有的礼物名称,重新查表是防止礼物变动
                $model = app('model_flying_supplement_gift')->getTable();
                $list = DB::table(\DB::raw(config('database.connections.mysql_flying.database')).'.'.$model.' as a')
                    ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
                    ->select([
                        'a.id',
                        'b.name as gift_name'
                    ])
                    ->whereIn('a.id', $newIdsArray)
                    ->pluck('gift_name','id')->toArray();
                $giftName = '';
                foreach ($info as $k => $v){
                    $idsArray = explode(',', $v['ids']);
                    foreach ($idsArray as $value){
                        $giftNewName = $list[$value] ?? '';
                        if (!empty($giftNewName)){
                            $giftName = $giftName.','.$giftNewName;
                        }
                    }
                    if (!empty($giftName)){
                        $giftName = ltrim($giftName, ',');
                    }
                    $info[$k]['gift_name'] = $giftName;
                    $giftName = '';
                }
            }
            return $info;
        }
    }

    /**
     * @Desc:暴击配置保存
     * @param $params
     * @return bool
     * @throws BasicException
     * @author: shiquan
     * @Time: 2023/3/8 15:28
     */
    public function criticalConfigSave($params)
    {
        $config = json_decode($params['config'], true);
        if (empty($config)){
            return true;
        }
        foreach ($config as $key => $value){
            if (!isset($value['level']) || !isset($value['rate']) || !isset($value['ids'])){
                throw new BasicException(0, '缺少参数');
            }

            if ($key == 0 && $value['level'] != 0){
                throw new BasicException(0, '阶段1默认应为0级');
            }
            if ($value['rate'] < 0 || $value['rate'] > 100){
                throw new BasicException(0, '概率有误,请检查');
            }
            if (empty($value['ids'])){  //补池配置表的自增id
                throw new BasicException(0, '配置序号不能为空');
            }
        }
        $info = app('model_flying_critical_config')->where('id', 1)->first();
        if (empty($info)){
            app('model_flying_critical_config')->insert([
                'id' => 1,
                'config' => $params['config'],
                'update_time' => time()
            ]);
        } else {
            $params['update_time'] = time();
            app('model_flying_critical_config')->where('id', 1)->update($params);
        }
        return true;
    }
}
